package com.dwxt.community.aiequipment.sellmachine.service;

import com.alipay.api.*;
import com.alipay.api.internal.util.*;
import com.dwxt.common.base.*;
import com.dwxt.common.util.*;
import com.dwxt.common.wxpay.*;
import com.dwxt.common.zfbpay.*;
import com.dwxt.community.aiequipment.sellmachine.entity.*;
import com.dwxt.community.dao.*;
import org.slf4j.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.stereotype.*;
import org.springframework.transaction.annotation.*;

import java.util.*;

/**
 * @program: intelligentcity
 * @description: 售卖机订单服务层
 * @author: shenwenkang
 * @create: 2020/05/20
 */
@Service
public class SellMachineOrderService {

    private Logger log = LoggerFactory.getLogger(SellMachineOrderService.class);
    @Autowired
    private SellMachineOrderMapper sellMachineOrderMapper;
    @Autowired
    private SellMachineAisleMapper sellMachineAisleMapper;
    @Autowired
    private SellMachineGoodsBuyRecordMapper sellMachineGoodsBuyRecordMapper;

    public String checkParamsWX(String notifyData) throws Exception {

        String xmlBack = "";
        Map<String, String> notifyMap = null;
        MyWXPayConfig myWXPayConfig = new MyWXPayConfig();
        WXPay wxpay = new WXPay(myWXPayConfig);
        notifyMap = WXPayUtil.xmlToMap(notifyData);         // 转换成map
        if (wxpay.isPayResultNotifySignatureValid(notifyMap)) {
            // 签名正确
            String return_code = notifyMap.get("return_code");//状态
            String out_trade_no = notifyMap.get("out_trade_no");//订单号
            SellMachineOrder order = sellMachineOrderMapper.selectByPrimaryKey(out_trade_no);
            if (out_trade_no == null || !return_code.equalsIgnoreCase("SUCCESS")) {
                log.info("微信支付回调失败订单号: {}", notifyMap);
                xmlBack = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" +
                        "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
                return xmlBack;
            } else {
                xmlBack = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>" +
                        "<return_msg><![CDATA[SUCCESS]]></return_msg>" + "</xml> ";
                // 业务逻辑处理 ****************************
                //更改订单状态
                changOrderWithWxAndZFBPay(order);

                log.info("微信支付回调成功订单号: {}", notifyMap);
                return xmlBack;
            }
        } else {
            log.error("微信支付回调通知签名错误");
            xmlBack = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" +
                    "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
            return xmlBack;
        }
    }

    /**
     * 修改订单状态、售卖机数据情况
     */
    @Transactional(rollbackFor = Exception.class)
    public void changOrderWithWxAndZFBPay(SellMachineOrder order) {
        //生成购买记录记录
        SellMachineGoodsBuyRecord sellMachineGoodsBuyRecord = new SellMachineGoodsBuyRecord();
        sellMachineGoodsBuyRecord.setRecordId(IDUtils.genItemId());
        sellMachineGoodsBuyRecord.setAisleNo(order.getAisleNo());
        sellMachineGoodsBuyRecord.setDeviceId(order.getSellMachineId());
        sellMachineGoodsBuyRecord.setOrderId(order.getOrderId());
        sellMachineGoodsBuyRecord.setGoodsId(order.getGoodsId());
        Date date = new Date();
        sellMachineGoodsBuyRecord.setRecordCreateTime(date);
        sellMachineGoodsBuyRecord.setRecordUpdateTime(date);
        sellMachineGoodsBuyRecord.setGoodsPrice(order.getOrderPrice());
        sellMachineGoodsBuyRecordMapper.insert(sellMachineGoodsBuyRecord);
        //修改订单状态
        order.setOrderStatus(YesOrNo.YES);
        order.setUpdateTime(new Date());
        sellMachineOrderMapper.updateByPrimaryKeySelective(order);
        //修改货道信息
        SellMachineAisle sellMachineAisle = sellMachineAisleMapper.selectAisleInfo(order.getSellMachineId(), order.getAisleNo()).get(0);
        sellMachineAisle.setCurrentNum(sellMachineAisle.getCurrentNum() - 1);
        sellMachineAisleMapper.updateByPrimaryKeySelective(sellMachineAisle);
        log.info("第三放支付回调修改状态成功！");
    }


    public String checkParamsZFB(Map<String, String> params) throws AlipayApiException {
        boolean signVerified = AlipaySignature.rsaCheckV1(params, ZFBConfig.publicKey, ZFBConfig.charset, ZFBConfig.signType);
        //对验签进行处理
        log.info("result:1");
        if (signVerified) {  //验签通过
            String out_trade_no = params.get("out_trade_no");// 商户订单号
            SellMachineOrder order = sellMachineOrderMapper.selectByPrimaryKey(out_trade_no);
            if ("TRADE_SUCCESS".equals(params.get("trade_status"))) {
                changOrderWithWxAndZFBPay(order);
                return "success";
            } else {
                log.info("result:4");
            }
        }
        log.info("result:5");
        return "fail";
    }
}
